<template>
  <Dialog :appDialog="appDialog" ref="DialogRef">
    <el-form ref="ruleFormRef" :model="formData" :rules="rules" class="m_r_t">
      <el-form-item label="属性名称" prop="attr_name">
        <el-input class="input_w" maxlength="15" show-word-limit v-model="formData.attr_name" placeholder="请输入属性名称"></el-input>
      </el-form-item>
      <el-form-item label="属性格式" prop="attr_type">
        <el-select  class="input_w"  v-model="formData.attr_type" placeholder="请选择属性格式">
          <el-option v-for="item in typeList" :key="item.label" :value="item.value" :label="item.label"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item v-if="formData.attr_type == 'select' || formData.attr_type == 'muti_select'" label="选项内容" prop="content">
        <el-input  class="input_w" v-model="formData.content" type="textarea" placeholder="每个选项为一行，最多30个选项"></el-input>
      </el-form-item>
      <el-form-item label="编辑排序" prop="weight">
        <el-input-number  class="input_w"  v-model="formData.weight" :min="0" controls-position="right" placeholder="请输入排序" />
      </el-form-item>
      <el-form-item label="是否开启" prop="is_enable">
        <el-radio-group v-model="formData.is_enable">
          <el-radio :label="1">开启</el-radio>
          <el-radio :label="2">关闭</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="是否必填" prop="is_required">
        <el-select  class="input_w"  v-model="formData.is_required" placeholder="请选择属性格式">
          <el-option :value="2" label="是"></el-option>
          <el-option :value="1" label="否"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
  </Dialog>
</template>

<script setup lang="ts">
  import Dialog from '@/components/Dialog.vue'
  import type { ElForm } from 'element-plus'
  import { ElMessage } from 'element-plus'
  import { reactive, ref, watch } from 'vue'
  import { attrCreate, attrEdit } from '@/api/customer/clubManage/clueSetting'
  type FormInstance = InstanceType<typeof ElForm>
  const ruleFormRef = ref<FormInstance>()
  const DialogRef = ref({})
  const emit = defineEmits(['save'])
  const formData: any = ref({})
  const titles = ref()
  const rules = ref({
    weight: { required: true, message: '请输入编辑排序' },
    attr_name: { required: true, message: '请输入属性名称' },
    content: { required: true, message: '请输入选项内容' },
    is_enable: { required: true, message: '请选择开启或关闭' },
    attr_type: { required: true, message: '请选择属性格式' },
    is_required: { required: true, message: '请选择是否必选' }
  })
  // 属性格式列表
  const typeList = reactive([
    { label: '单行文本', value: 'textbox' },
    { label: '多行文本', value: 'textarea' },
    { label: '单选', value: 'select' },
    { label: '多选', value: 'muti_select' },
    { label: '日期', value: 'date' },
    { label: '手机号', value: 'mobile' },
    { label: '邮箱', value: 'email' },
    { label: '区域', value: 'pca' },
    { label: '图片', value: 'picture' }
  ])

  let oldContentArr: any = [] //老的选择的选项数据 默认是空  用于编辑
  const initForm = () => {
    oldContentArr = []
    formData.value = {
      attr_name: '',
      attr_type: '',
      content: '',
      weight: 0,
      is_enable: 1,
      is_required: 1
    }
  }
  // 取消
  const cancelHandel = () => {
    ruleFormRef.value?.resetFields()
    appDialog.value.visible = false
  }

  const getContentArr = (str: string) => {
    if (!str.trim().length) {
      return []
    }
    let arr: any = []
    str.split('\n').forEach((item) => {
      if (item.length > 0) {
        arr.push(item)
      }
    })
    arr = Array.from(new Set(arr)) //去除重复的
    return arr
  }

  // 新建客户属性
  const attrCreateFun = (param: object) => {
    attrCreate(param).then((r: object) => {
      cancelHandel()
      emit('save')
      ElMessage.success('创建成功')
    })
  }

  //编辑更改客户属性
  const editAttrFun = (param: object) => {
    attrEdit(param).then((r: object) => {
      cancelHandel()
      emit('save')
      ElMessage.success('更新成功')
    })
  }

  // 保存
  const submitHandel = () => {
    ruleFormRef.value?.validate((valid) => {
      if (valid) {
        let { attr_name, attr_type, weight, is_enable, content, id, is_required } = formData.value
        let nowContentArr = getContentArr(content)
        let isEdit = oldContentArr.length
        if (attr_type != 'select' && attr_type != 'muti_select') {
          nowContentArr = []
        }
        //   oldContentArr 有值编辑 没有创建
        if (oldContentArr.length > 0 || isEdit || id) {
          let attr_val: any = [] //新增了哪些
          nowContentArr.forEach((item: string) => {
            let indx = oldContentArr.findIndex((it: any) => {
              return it == item
            })
            if (indx == -1) {
              attr_val.push(item)
            }
          })
          editAttrFun({ attr_name, attr_type, weight, is_enable, attr_val: nowContentArr, attr_id: id, is_required })
        } else {
          attrCreateFun({ attr_name, attr_type, weight, is_enable, attr_val: nowContentArr, is_required })
        }
      }
    })
  }
  // 检查是否输入标准  防止ssr
  const checkTextarea = () => {
    let str = formData.value.content
    str = str.replace(/<script>/g, '')
    str = str.replace(/alert/g, '')
    formData.value.content = str
  }
  const appDialog: any = ref({
    visible: false,
    title: titles,
    width: '600px',
    cancel: cancelHandel,
    submit: submitHandel,
    cancelText: '取消',
    submitText: '保存',
    editData: {} //当前编辑的数据
  })
  // 监听弹窗 是否为编辑
  watch(
    () => appDialog.value.visible,
    (val: boolean) => {
      if (val) {
        initForm()
        if (appDialog.value.editData.id) {
          let { name, id, weight, attr_val_name, type, is_enable, is_required } = appDialog.value.editData
          console.log(appDialog.value.editData, 'appDialog.value.editData')
          is_required = is_required ? is_required : 2
          attr_val_name = attr_val_name ? attr_val_name.split(',') : attr_val_name
          oldContentArr = attr_val_name ? attr_val_name : []
          let content = attr_val_name ? attr_val_name.toString().replace(/,/g, '\n') : ''
          formData.value = Object.assign(formData.value, { attr_name: name, id, weight, attr_type: type, is_enable, content, is_required })
          console.log(formData.value, 'formData.value')
          appDialog.value.editData = {}
        }
      }
    }
  )

  defineExpose({
    appDialog,
    titles
  })
</script>

<style lang="scss" scoped>
  .m_r_t {
    margin-top: 14px;
  }
  .input_w {
    width: 400px
  }
</style>
